package Controller;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;

import Model.RequestHandler;

/*
 * Analyze the message - 
 * 		pull data if not dummy (reperesented by -1 index)
 * 		push data if not dummy
 * */
public class Request extends Thread 
{
	// when there is no data to pull, send this
	private byte[] DUMMY_PULL = {1};
	
	private Socket m_Socket;

	public Request(Socket connSocket) 
	{
		m_Socket = connSocket;
	}
	
	@Override
	public void run()
	{
		DataInputStream in = null;
		DataOutputStream out = null;
		
		try
		{
			// client's input/output
			in = new DataInputStream(m_Socket.getInputStream());
			out = new DataOutputStream(m_Socket.getOutputStream());
        
			// get client's request
			byte[] message = null;
			int length = in.readInt();
			if(length>0) 
			{
			    message = new byte[length];
			    in.readFully(message, 0, message.length); 
			}
	        
	        // process request
	        RequestHandler handler = new RequestHandler(message);	        
	 
	        // acquire pull data
	        byte[] result = handler.pull();
	        if (result == null || result.length <= 1)
	        {
	        	result = DUMMY_PULL;
	        }

	        // send data back
	        out.writeInt(result.length); 
	        out.write(result);
	        
	        // store new data
        	handler.push();
		}
		catch(Exception e)
		{
			
		}
		finally
		{
			// close connections
			
			try
			{
				out.close();
			}
			catch(Exception e)
			{
				
			}
			
			try
			{
				in.close();
			}
			catch(Exception e)
			{
				
			}
			
			try
			{
				m_Socket.close();
			}
			catch(Exception e)
			{
				
			}
		}
	}
}
